﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Parlez.Controller
{
    public abstract class MultiLingualController : System.Web.Mvc.Controller
    {

        private Utilities.Utils _Class_Utilities = new Utilities.Utils();
        private string _MultiLingualCookie_String = "MLanguageSelection";
        private LanguageSelectors.LanguageSelector _Selector_LanguageSelector = LanguageSelectors.LanguageSelectorFactory.GetLanguageSelector();

        protected override void ExecuteCore()
        {
            string _CurrentLanguage_String = GetCurrentCulture();

            System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo(_CurrentLanguage_String);
            RouteData.Values["lang"] = System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

            _Class_Utilities.SetCookie(_MultiLingualCookie_String, System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName);

            base.ExecuteCore();
        }

        protected string GetDictionaryItem(string Key, string Default)
        {
            return _Selector_LanguageSelector.GetLanguageItem(Key, Default);
        }

        protected override bool DisableAsyncSupport
        {
            get { return true; }
        }

        private string GetCurrentCulture()
        {
            String lang = String.Empty;

            if (RouteData.Values["lang"] != null && !String.IsNullOrWhiteSpace(RouteData.Values["lang"].ToString()))
            {
                return RouteData.Values["lang"].ToString();
            }

            if (!String.IsNullOrWhiteSpace(_Class_Utilities.GetCookieValue(_MultiLingualCookie_String)))
            {
                return _Class_Utilities.GetCookieValue(_MultiLingualCookie_String);
            }

            if ((ControllerContext.HttpContext.Request.UserLanguages != null) && (HttpContext.Request.UserLanguages.Length > 0))
            {
                return HttpContext.Request.UserLanguages[0];
            }

            return "en";
        }
    }
}
